package cn.qyd.kaoshi;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 邱运铎
 * @date 2024-03-24 0:35
 */
public class RottenOrangeUpgrade {
    public static void main(String[] args) {
        RottenOrangeUpgrade or = new RottenOrangeUpgrade();
        int[][] grid = new int[][]{{2,1,1},{1,1,0},{0,1,1}};
//        int[][] grid = new int[][]{{2,1,1},{0,1,1},{1,0,1}};
        int result = or.orangesRotting(grid);
        System.out.println(result);
    }
    public int orangesRotting(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;

        Queue<int[]> queue = new LinkedList<>();
        int count = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    count++;
                } else if (grid[i][j] == 2) {
                    queue.add(new int[]{i,j});
                }
            }
        }

        int round = 0;
        while (count > 0 && !queue.isEmpty()) {
            round++;
            int size = queue.size();
            for (int k = 0; k < size; k++) {
                int[] rotten = queue.poll();
                int i = rotten[0];
                int j = rotten[1];
                if (i - 1 >= 0 && grid[i - 1][j] == 1) {
                    grid[i - 1][j] = 2;
                    count--;
                    queue.add(new int[]{i - 1,j});
                }
                if (i + 1 < m && grid[i + 1][j] == 1) {
                    grid[i + 1][j] = 2;
                    count--;
                    queue.add(new int[]{i + 1,j});
                }
                if (j - 1 >= 0 && grid[i][j - 1] == 1) {
                    grid[i][j - 1] = 2;
                    count--;
                    queue.add(new int[]{i,j - 1});
                }
                if (j + 1 < n && grid[i][j + 1] == 1) {
                    grid[i][j + 1] = 2;
                    count--;
                    queue.add(new int[]{i,j + 1});
                }
            }
        }

        if (count > 0) {
            return -1;
        } else {
            return round;
        }
    }
}
